<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item label="计划编号" prop="planNo">
        <el-input v-model="queryParams.planNo" placeholder="请输入计划编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="车间" prop="deptId">
        <treeselect v-model="queryParams.deptId" :options="deptList" :normalizer="normalizer" placeholder="选择所属车间"
          style="width: 200px" />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品编码" prop="productCode">
        <el-input v-model="queryParams.productCode" placeholder="请输入产品编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工艺路线名称" prop="processRouteName">
        <el-input v-model="queryParams.processRouteName" placeholder="请输入工艺路线名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工艺路线类型" prop="routeType">
        <el-select v-model="queryParams.routeType" placeholder="请选择工艺路线类型" clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.ROUTE_TYPE)" :key="dict.value" :label="dict.label"
            :value="parseInt(dict.value)" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.PLAN_STATUS)" :key="dict.value" :label="dict.label"
            :value="parseInt(dict.value)" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <!--      <el-col :span="1.5">-->
      <!--        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"-->
      <!--                   :loading="exportLoading"-->
      <!--                   v-hasPermi="['warehouse:order-in:export']">导出-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      :row-key="getRowKey"
      @selection-change="handleRowCheckboxChange"
      @expand-change="handleExpand"
    >
      <el-table-column type="expand">
        <template v-slot="props">
          <el-table  :data="props.row.workOrderList || []" border style="width: 98%;margin: 0 auto"
                    header-row-class-name="custom-header-row">
            <el-table-column type="index" label="序号" width="80" align="center"/>
            <el-table-column label="工单号" align="center" prop="workOrderNo" width="200"/>
            <el-table-column label="工序订单编号" align="center" prop="procedureWorkOrderNo" width="200"/>
            <el-table-column label="计划编号" align="center" prop="planNo" width="200"/>
            <el-table-column label="车间名称" align="center" prop="deptName" width="200"/>
            <el-table-column label="产品名称" align="center" prop="productName" width="200"/>
            <el-table-column label="产品编码" align="center" prop="productCode" width="200"/>
            <el-table-column label="物料编码" align="center" prop="materialNo" width="200"/>
            <el-table-column label="物料名称" align="center" prop="materialName" width="200"/>
            <el-table-column label="工序编号" align="center" prop="procedureCode" width="200"/>
            <el-table-column label="工序名称" align="center" prop="procedureName" width="200"/>
            <el-table-column label="设备编号" align="center" prop="deviceCode" width="200"/>
            <el-table-column label="设备名称" align="center" prop="deviceName" width="200"/>
            <el-table-column label="工单顺序" align="center" prop="sort" width="200"/>
            <el-table-column label="工单数量" align="center" prop="workOrderQuantity" width="200"/>
            <el-table-column label="计划开始时间" align="center" prop="planBeginTime" width="180">
              <template v-slot="scope">
                <span>{{ parseTime(scope.row.planBeginTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="计划结束时间" align="center" prop="planEndTime" width="180">
              <template v-slot="scope">
                <span>{{ parseTime(scope.row.planEndTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="实际开始时间" align="center" prop="actualBeginTime" width="180">
              <template v-slot="scope">
                <span>{{ parseTime(scope.row.actualBeginTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="实际结束时间" align="center" prop="actualEndTime" width="180">
              <template v-slot="scope">
                <span>{{ parseTime(scope.row.actualEndTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="已完成数量" align="center" prop="completeQuantity" width="200"/>
            <el-table-column label="每日派工数量" align="center" prop="daySendWorkNumber" width="200"/>
            <el-table-column label="状态" align="center" prop="status">
              <template v-slot="scope">
                <span>{{ getDictDataLabel(DICT_TYPE.WORKORDER_STATUS, scope.row.status) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="180">
              <template v-slot="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="完成进度" align="center" width="180">
                <template v-slot="scope">
                  <el-progress
                    :text-inside="true"
                    :stroke-width="16"
                    :percentage="calculateProgress(scope.row)"
                    class="progress-white-text"
                  ></el-progress>
                </template>
             </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column type="selection" width="55"/>
      <el-table-column label="计划编号" align="center" prop="planNo" width="200" />
      <el-table-column label="生产订单号" align="center" prop="extCode" width="200" />
      <el-table-column label="车间名称" align="center" prop="deptName" width="150" show-overflow-toolti />
      <el-table-column label="产品名称" align="center" prop="productName" width="200" show-overflow-tooltip />
      <el-table-column label="产品编码" align="center" prop="productCode" width="200" show-overflow-tooltip />
      <el-table-column label="工单数量" align="center" prop="planQuantity" width="120" />
      <el-table-column label="报工数量" align="center" prop="completeQuantity" width="120" />
      <el-table-column label="工艺路线名称" align="center" prop="processRouteName" width="200" show-overflow-tooltip />
      <el-table-column label="工艺路线类型" align="center" prop="routeTypeName" width="200" show-overflow-tooltip />
      <el-table-column label="计划开始时间" align="center" prop="planBeginTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.planBeginTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划结束时间" align="center" prop="planEndTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.planEndTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际开始时间" align="center" prop="actualBeginTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.actualBeginTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际结束时间" align="center" prop="actualEndTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.actualEndTime) }}</span>
        </template>
      </el-table-column>


      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" fixed="right">
        <template v-slot="scope">
          <span>{{ getDictDataLabel(DICT_TYPE.PLAN_STATUS, scope.row.status) }}</span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!-- 对话框(添加 / 修改) -->
  </div>
</template>

<script>
import * as ReportApi from '@/api/report/planReport';
import * as PlanApi from '@/api/production/plan';
import * as WorkOrderApi from '@/api/production/workorder';
import {getDictDatas, getDictDataLabel, DICT_TYPE} from '@/utils/dict'
import {listDept} from "@/api/system/dept";
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';

export default {
  name: "PlanReport",
  components: {
    Treeselect
  },
  data() {
    return {
      // 部门列表
      deptList: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 列表数据
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 选中行
      currentRow: {},
      checkedIds: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        planNo: null,
        deptId: null,
        productName: null,
        productCode: null,
        processRouteName: null,
        routeType: null,
        status: null
      },
    };
  },
  created() {
    this.getList();
    this.getOptions();
  },
  methods: {
    // 打开出库弹框
    inOrOut(child, father) {
      // 初始化表单数据
      this.outFormData = {
        id: child.id,
        materialId: child.materialId,
        materialName: child.materialName,
        batchNo: child.batchNo || '',
        outWarehouseId: father.outWarehouseId,
        outStoreId: father.outStoreId,
        quantity: child.quantity
      };

      // 如果有选择仓库，加载对应的库位列表
      if (father.outWarehouseId) {
        this.getInOrOutLocationList(father.outWarehouseId);
      } else {
        this.inOrOutIocationList = [];
      }

      // 显示弹框
      this.outDialogVisible = true;
    },

    // 出库弹框中仓库选择变化
    async handleOutWarehouseChange(warehouseId) {
      this.outFormData.outStoreId = null;
      if (warehouseId) {
        await this.getInOrOutLocationList(warehouseId.id);
      } else {
        this.inOrOutIocationList = [];
      }
    },

    // 获取出库弹框专用库位列表
    async getInOrOutLocationList(warehouseId) {
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          warehouseId: warehouseId
        };
        const res = await LocationApi.getLocationPage(params);
        this.inOrOutIocationList = res.data.list;
      } catch (error) {
        console.error('获取出库库位列表失败:', error);
        this.inOrOutIocationList = [];
      }
    },

    // 关闭出库弹框
    handleOutDialogClose() {
      this.outDialogVisible = false;
      this.$refs.outFormRef && this.$refs.outFormRef.resetFields();
    },

    // 确认出库
    async handleOutConfirm() {
      try {
        // 构建请求参数
        const params = {
          id: this.outFormData.id,
          outStoreId: this.outFormData.outStoreId,
          materialId: this.outFormData.materialId,
          batchNo: this.outFormData.batchNo,
          quantity: this.outFormData.quantity
        };

        // 调用出库接口
        await ReportApi.inOrOut(params);

        // 关闭弹框
        this.outDialogVisible = false;

        // 刷新列表
        await this.getList();

        // 提示成功
        this.$modal.msgSuccess('入库成功');
      } catch (error) {
        console.error('入库失败:', error);
        this.$modal.msgError('入库失败');
      }
    },

    // 完结单据
    async overForm(row) {
      try {
        // 二次确认对话框
        await this.$confirm('确定要完结该单据吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        // 调用完结接口，传递整行数据
        await ReportApi.finish(row);

        // 刷新列表
        this.getList();

        // 提示成功
        this.$modal.msgSuccess('单据完结成功');
      } catch (error) {
        // 如果是用户取消确认，不显示错误信息
        if (error !== 'cancel') {
          console.error('单据完结失败:', error);
          this.$modal.msgError('单据完结失败');
        }
      }
    },
    /** 获取行数据的唯一标识 */
    getRowKey(row) {
      return row.id;
    },

    /** 查询列表 */
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const res = await PlanApi.getPlanPage(this.queryParams);
        // 初始化每一行的工单列表
        this.list = res.data.list.map(item => ({
          ...item,
          workOrderList: []
        }));
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },
    /** 处理表格展开行 */
    async handleExpand(row, expandedRows) {
      // 如果是展开操作且没有加载过数据
      if (expandedRows.includes(row) && (!row.workOrderList || row.workOrderList.length === 0)) {
        try {
          const res = await WorkOrderApi.getWorkOrderPage({
            pageNo: 1,
            pageSize: 100,
            planId: row.planId || row.id
          });
          row.workOrderList = res.data.list;
        } catch (error) {
          console.error('获取工单数据失败:', error);
          this.$modal.msgError('获取工单数据失败');
          row.workOrderList = [];
        }
      }
    },
    normalizer(node) {
      // 构建基础对象，确保包含 id, label, children 属性
      // 关键：如果不是第三级节点，则禁用
      return {
        id: node.id,
        label: node.name,
        children: node.children, // 必须包含 children
      };
    },
    getOptions() {
      listDept().then(response => {
        this.deptList = this.handleTree(response.data, "id")[0]?.children || [];
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加/修改操作 */
    openForm(id, isDetail = false) {
      this.$refs["formRef"].open(id, isDetail);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除仓库单据编号为"' + id + '"的数据项?')
      try {
        await ReportApi.deleteOrder(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    /** 批量删除仓库单据 */
    async handleDeleteBatch() {
      await this.$modal.confirm('是否确认删除?')
      try {
        await ReportApi.deleteOrderList(this.checkedIds);
        this.checkedIds = [];
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    handleRowCheckboxChange(records) {
      this.checkedIds = records.map((item) => item.id);
    },

    /* 计算完成进度百分比 */
    calculateProgress(row) {
      // 处理completeQuantity不存在或为0的情况
      const completeQuantity = row.completeQuantity || 0;
      const workOrderQuantity = row.workOrderQuantity || 0;

      // 避免除以0的错误，当工单数量为0时返回0
      if (workOrderQuantity === 0) {
        return 0;
      }

      // 计算百分比并确保在0-100之间
      const percentage = (completeQuantity / workOrderQuantity) * 100;
      return Math.min(100, Math.max(0, percentage));
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有仓库单据数据项?');
      try {
        this.exportLoading = true;
        const data = await ReportApi.exportOrderExcel(this.queryParams);
        this.$download.excel(data, '仓库单据.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },
  }
};
</script>
<style scoped>
/* 使用深度选择器确保样式能正确应用到子表格表头 */
::v-deep .custom-header-row th {
  background-color: #659cdb !important;
  color: white;
}

/* 确保表头单元格也应用样式 */
::v-deep .custom-header-row .cell {
  color: white;
}

/* 进度条内文字颜色为白色 */
::v-deep .progress-white-text .el-progress-bar__innerText {
  color: white;
}
</style>
